package controller_jcj

import (
	"github.com/gin-gonic/gin"
	"github.com/gin-gonic/gin/binding"
	"tools-api/src/jcj/model"
	"tools-api/src/jcj/service/service_user"
	"tools-api/src/routes/request"
	"tools-api/src/routes/response"
)

// VerifyAccess 校验Token权限
func VerifyAccess(ctx *gin.Context) {
	ip := request.GetClientIP(ctx)
	exist := model.UserIpLimit{}.Exist(ip)
	if exist {
		response.FailByCode(ctx, response.RequestForbidden, "禁止访问")
		return
	}
	uuid, err := service_user.AccessTokenVerify(request.GetAccessToken(ctx), request.GetDeviceType(ctx), request.GetDeviceId(ctx))
	if err != nil {
		response.FailByCode(ctx, response.AccessTokenInvalid, "令牌过期")
		return
	}

	ctx.Set(request.JcjHeaderKeyUUID, uuid) // 缓存用户信息 TODO 如果有需要可以扩展
	ctx.Next()                              // 继续
}

// AccessTokenExchange 刷新AccessToken
func AccessTokenExchange(ctx *gin.Context) {
	var req struct {
		Token string `json:"token"`
	}
	_ = ctx.ShouldBindBodyWith(&req, binding.JSON)
	token, err := service_user.AccessTokenExchange(req.Token, request.GetDeviceType(ctx), request.GetDeviceId(ctx))
	if err != nil {
		response.FailByCode(ctx, response.RefreshTokenInvalid, "令牌过期")
		return
	}
	response.Success(ctx, token)
}
